<?php 
namespace app\houtai\controller\server;

use app\houtai\controller\BaseController;
use app\houtai\controller\RedisHash;
use think\Db;
use think\Request;
use think\db\Expression;
use think\paginator\driver\Bootstrap;


class LinusrvController extends BaseController{
  
  
	/**
	  *  @brief  : LINUX远程控制
	  *  @return : page
	  *  @details: 
	*/

	public function indexAction() {
    $type = $this->request->param("type/d",0);
    $git = $this->request->param("git/s",'');
    $name = config('auth.session');
    $auid = session($name);   // 取值（当前作用域）
    $roleID = table("Ky_Admin","rydb.websms")->where(["AdminId"=>$auid])->find();
    $LinuxConfig = table("LinuxConfig","rydb.websms")->where(["Status"=>1])->order("CreateTime","desc")->find();
    $status = 0;   //默认0没有空置的服务器
    $linuxids = 100; //默认状态值100，前段命令按钮样式为不可操作
    if ($type == 5 and $git == ''){
        return result(['cmd'=>'请填写正确的Git地址','err'=>'Git地址为空','linuxid'=>5],0,'请填写正确的Git地址');
    }
    if ($roleID['RoleID']!=2) {
      echo "<script>alert('无权查看此页面'),window.location.href='/index/home';</script>";
    }
    if ($type <= 0) {
      if (count($LinuxConfig) > 0) {
        $status = 1;
        $linuxids = $roleID['LinuxID'];
      }else{
        echo "<script>alert('没有空置服务器,如需开服请点击右上配置服务');</script>";
      }
      return $this->fetch('',['linuxid'=>$linuxids,'Status'=>$status]);
    }elseif ($type==1) {

      $root = $this->request->param("root/s",'root');
      $pwd = $this->request->param("pwd/s",'');
      $host = $this->request->param("host/s",'');
      $port = $this->request->param("port/d",22);
      $status = 1;
      table('LinuxConfig','rydb.websms')->insert(['root'=>$root,'pwd'=>$pwd,'host'=>$host,'port'=>$port,'Status'=>$status]);
      return result([],0,'创建成功');
    }{	 
	    
      $ssh_user=$LinuxConfig['root']; //登陆linux的ssh2用户名
      $ssh_pwd =$LinuxConfig['pwd'];  //登陆linux的密码
      $ssh_port=$LinuxConfig['port']; //端口号22
      $ssh_host=$LinuxConfig['host']; //服务器IP地址
      if(!function_exists("ssh2_connect")){
          exit('SSH扩展没有安装或者没有安装成功');
      };
      $ssh2 = ssh2_connect($ssh_host, $ssh_port);
      if(!$ssh2){
          return result(['err'=>'连接服务器失败'],101);
      }else{
         
          $outputs='成功连接上了服务器'.$ssh_host.':'.$ssh_port.'请仔细核对服务地址';
      }
      //连接成功后进行密码验证，没验证无法进行其他操作。
      if(!ssh2_auth_password( $ssh2, $ssh_user,  $ssh_pwd )){
          return false;
      }
      switch ($type) {
        case '200':
          
          $shell="go version;docker --version;";
          break;
        case '3':
          $outputs = '执行Go脚本命令';
//          $shell='cd /;ls -l;';
           $shell = "mkdir /Adobe;cd /Adobe;wget https://dl.google.com/go/go1.13.linux-amd64.tar.gz;cd /Adobe;tar -zxvf go1.13.linux-amd64.tar.gz -C /usr/local/;sudo ln -s /usr/local/go/bin/* /usr/bin/;go env -w GOPROXY=https://goproxy.cn,direct;go env -w GO111MODULE=on;go version;go env;";
          break;
        case '4':
          $outputs = '执行Docker脚本命令';
           $shell = "yum -y install docker;systemctl start docker;systemctl enable docker.service;systemctl status docker;Yum install gcc-c++ -y;";
          
//          $shell="cd /;ls -l;";
            break;  
        case '5' :
           $outputs = '执行Git脚本命令';
           $shell="cd /home;mkdir code;cd code;ls -l;git clone http://".$git;

            break; 
        case '6':
          $outputs = '执行镜像脚本命令';
           $shell="sudo docker login --username=docker_yg --password=xiaominzi0422 registry.cn-hangzhou.aliyuncs.com;docker pull registry.cn-hangzhou.aliyuncs.com/games_yg/centos:v5;";
          
//           $shell="cd /;ls -l;";
            break; 
        case '7':
          $outputs = '执行修改配置文件脚本命令';
         $shell="mv /home/code/2019_goserver/src/games/libs/libprotobuf.a /home/code/2019_goserver/src/games/libs/libprotobuf_bak.a;mv /home/code/2019_goserver/src/games/libs/libprotobuf_linux.a /home/code/2019_goserver/src/games/libs/libprotobuf.a;cd /home/code/2019_goserver/src/games/libs;ls -l;";
//          $shell="cd /;ls -l;";
          
            break; 
        case '8':
          $outputs = '结束链接';
          $shell="cd /;ls -l;";  
            break;
                       
        default:
          $shell="cd /;ls -l;";
          break;
      }
      // $shell = "mkdir /Adobe;cd /Adobe;wget https://dl.google.com/go/go1.13.linux-amd64.tar.gz";
      // $shell = "cd /Adobe;ls;tar -zxvf go1.13.linux-amd64.tar.gz -C /usr/local/";
      // $shell = "vim ~/.bash_profile;";
      // $shell = "cd /;ls -l;go version;go env";
      // $shell = "shutdown -r now";
      $b = ssh2_exec($ssh2,$shell);
      $dio_stream = ssh2_fetch_stream($b,SSH2_STREAM_STDERR);  //获得标准输入输出留
      stream_set_blocking($dio_stream, true);
      stream_set_blocking($b, true);
      $output = stream_get_contents($b);
      $result_dio = stream_get_contents($dio_stream); //获取流的内容，即命令的返回内容
      if ($result_dio == '' and $type != 200) {
          $linux = table('Ky_Admin','rydb.websms')->where(['AdminId'=>$auid])->update(['LinuxID'=>$type]);
          
      }
      if ($type == 8) {
        table("LinuxConfig","rydb.websms")->where(['Status'=>1])->update(['Status'=>0]);
      }
      $linuxID = table('Ky_Admin','rydb.websms')->where(['AdminId'=>$auid])->value('LinuxID');
      return result(['cmd'=>$output,'err'=>$result_dio,'linuxid'=>$linuxID],0,$outputs);
      // fclose($b);
      
    }
   
	}

    /**
     *  @brief  : 服务开启列表配置
     *  @return : page
     *  @details:
     */
    public function  serconfAction(){
        $page = table('ServerConfig','rydb.websms')->paginate();
//        echo "<pre/>";
//        print_r($page);die;
        return $this->fetch('',[
            'page'=>$page
        ]);
    }

    /**
     *  @brief  : 服务配置详情
     *  @return : page
     *  @details:
     */
    public function srvdetailAction(){
        $id = $this->request->param('id/d', 1);
        $Channel = table('ServerConfig', 'rydb.websms')->where(['ID' => $id])->find();
        $data['ID'] = $Channel['ID'];
        $data['Channel'] = $Channel['Channel'];
        $data['ServerName'] = $Channel['ServerName'];
        $data['CreateTime'] = $Channel['CreateTime'];
        $data['UpdateTime'] = $Channel['UpdateTime'];
        $data['JsonData'] = json_decode($Channel['JsonData'],true);

        if ($this->request->isGet()) {
            return $this->fetch('', ['row' => $data ?? []]);
        }
        if ($this->request->isPost()) {
            $data = $this->request->param();
            $res = [
                'App_config'=>[
                    'addr'=>$data['addr'],
                    'game_type'=>$data['game_type'],
                    'channel'=>$data['channel'],
                    'Weight'=>$data['Weight'],
                    'ipcAddr'=>$data['ipcAddr'],
                    'sid'=>$data['sid'],
                    'loghost'=>$data['loghost'],
                    'logdirname'=>$data['logdirname'],
                ],
                'redis_config'=>[
                    'host'=>$data['host'],
                    'port'=>$data['port'],
                    'network'=>$data['network']
                ],
                'mysql_config'=>[
                    'game'=>[
                        'host'=>$data['mshost'],
                        'port'=>$data['msport'],
                        'user'=>$data['msuser'],
                        'password'=>$data['mspassword'],
                        'db'=>$data['msdb']

                    ]
                ]
            ];
            $resdata = [
                'AppAddr'=>$data['addr'],
                'LogdirName'=>$data['logdirname'],
                'JsonData'=>json_encode($res),
                'UpdateTime'=>new Expression('GETDATE()')
            ];

            $re = table('ServerConfig','rydb.websms')->where('ID',$id)->update($resdata);
            if (!$re){
                return result([],101,$re);
            }
            return result([],0);
        }
    }
}
